package com.kkwrite.regimen.provider.service.collection;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.kkwrite.regimen.common.entity.dto.collection.CollectionDTO;
import com.kkwrite.regimen.provider.domain.RegCollectionDO;
import com.kkwrite.regimen.provider.domain.RegUserDO;
import com.kkwrite.regimen.provider.repository.RegCollectionRepository;
import com.kkwrite.regimen.provider.repository.RegUserRepository;

/**
 * @author jinying
 */
@Service("collectionService")
public class CollectionServiceImpl implements CollectionService {

    @Resource(name = "regCollectionRepository")
    private RegCollectionRepository regCollectionRepository;

    @Resource(name = "regUserRepository")
    private RegUserRepository regUserRepository;

    @Override
    public List<CollectionDTO> queryCollection(Long userId, Integer collectOwnerType) {
        List<CollectionDTO> regCollectionDTOList = new ArrayList<CollectionDTO>();
        List<RegCollectionDO> regCollectionDOList;
        if (collectOwnerType == null) {
            regCollectionDOList = regCollectionRepository.findAllByUserId(userId);
        } else {
            regCollectionDOList = regCollectionRepository.findAllByUserIdAndCollectOwnerType(userId, collectOwnerType);
        }
        if (regCollectionDOList != null && regCollectionDOList.size() > 0) {
            for (int i = 1; i < regCollectionDOList.size(); i++) {
                CollectionDTO collectionDto = new CollectionDTO();
                RegUserDO reguserDo = regUserRepository.findById(userId.intValue()).orElseThrow(RuntimeException::new);
                BeanUtils.copyProperties(regCollectionDTOList.get(i), collectionDto);
                BeanUtils.copyProperties(reguserDo, collectionDto);
                regCollectionDTOList.add(collectionDto);
            }
        }
        return regCollectionDTOList;
    }
}
